package com.gibs.peixunapi.service.impl;

import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

import com.gibs.peixunapi.VO.EditTestPaperVO;
import com.gibs.peixunapi.VO.SubjectHubVO;
import com.gibs.peixunapi.excepiton.BaseException;
import com.gibs.peixunapi.model.SubjectHub;
import com.gibs.peixunapi.model.TestPaper;
import com.gibs.peixunapi.service.SubjectHubService;
import com.gibs.peixunapi.service.TestPaperService;
import com.gibs.peixunapi.utils.ConverterUtil;
import org.springframework.beans.factory.annotation.Autowired;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.persistence.EntityNotFoundException;
import javax.validation.Valid;

import org.springframework.transaction.annotation.Transactional;
import com.gibs.peixunapi.enums.ResultEnum;
import com.gibs.peixunapi.result.Result;
import com.gibs.peixunapi.utils.ResultUtil;
import com.gibs.peixunapi.dao.TestPaperSubjectDao;
import com.gibs.peixunapi.service.TestPaperSubjectService;
import com.gibs.peixunapi.model.TestPaperSubject;

@Service
@Slf4j
@Transactional(rollbackFor = Exception.class)
public class TestPaperSubjectServiceImpl implements TestPaperSubjectService {

    @Autowired
    private TestPaperSubjectDao testPaperSubjectDao;
    @Autowired
    private SubjectHubService subjectHubService;
    @Autowired
    private TestPaperService testPaperService;

    @Transactional
    @Override
    public Result create(@Valid TestPaperSubject object) {
        try {

//			objectDao.save(object);
            return ResultUtil.success(ResultEnum.CREATE_SUCCESS);
        } catch (Exception e) {
            log.error(e.getMessage());
            return ResultUtil.error(ResultEnum.SERVER_ERROR);
        }
    }

    @Transactional
    @Override
    public Result save(@Valid TestPaperSubject object) {
        try {

//			TestPaperSubject testPaperSubject = objectDao.findOne(object.getId());
//			ConverterUtil.copyNotNullProperties(object,testPaperSubject);
//			objectDao.save(testPaperSubject);
            return ResultUtil.success(ResultEnum.UPDATE_SUCCESS);
        } catch (Exception e) {
            log.error(e.getMessage());
            return ResultUtil.error(ResultEnum.SERVER_ERROR);
        }
    }

    @Override
    public Result delete(Integer id) {
        try {
//			String[] ids = id.split(",");
//			for (String str : ids) {
//				objectDao.delete(Integer.valueOf(str));
//			}
            return ResultUtil.success(ResultEnum.DELETE_SUCCESS);
        } catch (Exception e) {
            log.error(e.getMessage());
            return ResultUtil.error(ResultEnum.SERVER_ERROR);
        }
    }


    @Override
    public Result get(Integer id) {
        try {
//			HashMap<String, Object> data = new HashMap<String, Object>();
//			TestPaperSubject object = objectDao.findOne(id);
//			if (object == null) {
//				Result(false, Status.FAILD, "查找失败", null);
//			}
//			HashMap<String,Object> map = new HashMap();
//			map.put("id", object.getId());
//			HashMap<String,Object> testPaperId = new HashMap<String,Object>();
//			testPaperId.put("name", object.getTestPaperId()==null?"":object.getTestPaperId().getName());
//			testPaperId.put("id", object.getTestPaperId()==null?"":object.getTestPaperId().getId());
//			map.put("testPaperId", testPaperId);
//			HashMap<String,Object> subjectHubId = new HashMap<String,Object>();
//			subjectHubId.put("name", object.getSubjectHubId()==null?"":object.getSubjectHubId().getName());
//			subjectHubId.put("id", object.getSubjectHubId()==null?"":object.getSubjectHubId().getId());
//			map.put("subjectHubId", subjectHubId);
//			HashMap<String,Object> creatorId = new HashMap<String,Object>();
//			creatorId.put("name", object.getCreatorId()==null?"":object.getCreatorId().getName());
//			creatorId.put("id", object.getCreatorId()==null?"":object.getCreatorId().getId());
//			map.put("creatorId", creatorId);
//			map.put("type", object.getType()==null?"":object.getType());
//			data.put("object",map);

            return ResultUtil.success(ResultEnum.FIND_SUCCESS);
        } catch (Exception e) {
            log.error(e.getMessage());
            return ResultUtil.error(ResultEnum.SERVER_ERROR);
        }
    }

    @Override
    public Result getList(String key) {
        try {
//			List<TestPaperSubject> list = new ArrayList<>();
//			if (!StringUtils.isEmpty(key)) {
//				list = objectDao.findLike("%" + key + "%");
//			} else {
//				list = objectDao.findAll();
//			}
//			if (list.size() == 0) {
//				PageResult(true, Status.OK, "无数据", new ArrayList(), 0L,0,0);
//			}
//			List<Object> data = new ArrayList<>();
//			for(TestPaperSubject object : list){
//				HashMap<String,Object> map = new HashMap();
//				map.put("id", object.getId());
//				HashMap<String,Object> testPaperId = new HashMap<String,Object>();
//				testPaperId.put("name", object.getTestPaperId()==null?"":object.getTestPaperId().getName());
//				testPaperId.put("id", object.getTestPaperId()==null?"":object.getTestPaperId().getId());
//				map.put("testPaperId", testPaperId);
//				HashMap<String,Object> subjectHubId = new HashMap<String,Object>();
//				subjectHubId.put("name", object.getSubjectHubId()==null?"":object.getSubjectHubId().getName());
//				subjectHubId.put("id", object.getSubjectHubId()==null?"":object.getSubjectHubId().getId());
//				map.put("subjectHubId", subjectHubId);
//				HashMap<String,Object> creatorId = new HashMap<String,Object>();
//				creatorId.put("name", object.getCreatorId()==null?"":object.getCreatorId().getName());
//				creatorId.put("id", object.getCreatorId()==null?"":object.getCreatorId().getId());
//				map.put("creatorId", creatorId);
//				map.put("type", object.getType()==null?"":object.getType());
//				data.add(map);
//			}
            return ResultUtil.success(ResultEnum.FIND_SUCCESS);
        } catch (Exception e) {
            log.error(e.getMessage());
            return ResultUtil.error(ResultEnum.SERVER_ERROR);
        }
    }

    @Override
    public Result getListPage(String key, Integer current, Integer limit) {
        try {
//			List<TestPaperSubject> list = new ArrayList<>();
//			limit = limit == null ? 10 : limit;
//			current = current == null ? 1 : current;
//			int offset = (current - 1) * limit;
//			Long total = null;
//			if (!StringUtils.isEmpty(key)) {
//				list = objectDao.findPageLike("%" + key + "%", offset, limit);
//				total = objectDao.countLike("%" + key + "%");
//			} else {
//				list = objectDao.findPage(offset, limit);
//				total = objectDao.count();
//			}
//			if (total == 0) {
//				PageResult(true, Status.OK, "无数据", new ArrayList(), 0L,0,0);
//			}
//			List<Object> data = new ArrayList<>();
//			for(TestPaperSubject object : list){
//				HashMap<String,Object> map = new HashMap();
//				map.put("id", object.getId());
//				HashMap<String,Object> testPaperId = new HashMap<String,Object>();
//				testPaperId.put("name", object.getTestPaperId()==null?"":object.getTestPaperId().getName());
//				testPaperId.put("id", object.getTestPaperId()==null?"":object.getTestPaperId().getId());
//				map.put("testPaperId", testPaperId);
//				HashMap<String,Object> subjectHubId = new HashMap<String,Object>();
//				subjectHubId.put("name", object.getSubjectHubId()==null?"":object.getSubjectHubId().getName());
//				subjectHubId.put("id", object.getSubjectHubId()==null?"":object.getSubjectHubId().getId());
//				map.put("subjectHubId", subjectHubId);
//				HashMap<String,Object> creatorId = new HashMap<String,Object>();
//				creatorId.put("name", object.getCreatorId()==null?"":object.getCreatorId().getName());
//				creatorId.put("id", object.getCreatorId()==null?"":object.getCreatorId().getId());
//				map.put("creatorId", creatorId);
//				map.put("type", object.getType()==null?"":object.getType());
//				data.add(map);
//			}
//			PageData pageData = new PageData(total, limit, current);
            return ResultUtil.successPage(ResultEnum.SUCCESS);
        } catch (Exception e) {
            log.error(e.getMessage());
            return ResultUtil.error(ResultEnum.SERVER_ERROR);
        }
    }


    @Override
    public Result getOptions(String key) {
        try {
//			List<TestPaperSubject> list = new ArrayList<>();
//			if (!StringUtils.isEmpty(key)) {
//				list = objectDao.findLike("%" + key + "%");
//			} else {
//				list = objectDao.findAll();
//			}
//			List<Object> data = new ArrayList<>();
//			for (TestPaperSubject object : list) {
//				HashMap<String, Object> map = new HashMap();
//				map.put("value", object.getId());
//				map.put("name", object.getSubjectHubId());
//				data.add(map);
//			}
            return ResultUtil.success(ResultEnum.SUCCESS);
        } catch (Exception e) {
            log.error(e.getMessage());
            return ResultUtil.error(ResultEnum.SERVER_ERROR);
        }
    }

    @Override
    public Map<String, List<SubjectHubVO>> getMapByTestPaper(Integer testPaperId) {

        List<SubjectHub> subjectHubList = testPaperSubjectDao.findSubjectHubListByTestPaperId(testPaperId);

        if (subjectHubList.isEmpty()) {
            throw new EntityNotFoundException();
        }
        Map<String, List<SubjectHubVO>> result = new HashMap<>();
        List<SubjectHubVO> temp = new ArrayList<>();
        /* 循环遍历转换为VO类 放入Map中返回结果*/
        for (int i = 0; i < subjectHubList.size(); i++) {
            SubjectHub subjectHub = subjectHubList.get(i);
            SubjectHubVO subjectHubVO = new SubjectHubVO();
            ConverterUtil.copyProperties(subjectHub, subjectHubVO, "knowPoint", "analysis");
            temp.add(subjectHubVO);
            /*如果下一个type不同那么结束收集此类型完毕*/
            if (subjectHubList.get(i).getType() != null) {
                if (subjectHubList.get(i).getType().equals(subjectHubList.get(i + 1).getType())) {
                    result.put(subjectHubList.get(i).getType(), temp);
                }
            }
        }
        return result;
    }


    @Override
    public TestPaper switchTestPaperSubject(List<SubjectHubVO> oldSubjectHubVOList, EditTestPaperVO newTestPaperVO) {

        //1.对比更新题目列表
        //把原先试卷列表转换成hashMap
        Map<Integer, SubjectHubVO> oldToNewMap = oldSubjectHubVOList.stream()
                .collect(Collectors.toMap(SubjectHubVO::getId, Function.identity()));
        //替换原有题目列表 使其成为新题目列表
        newTestPaperVO.getSubjectHubVOList().forEach(newOne -> {
            //新增题目版本
            Integer subjectId = subjectHubService.persist(newOne);
            //替换题目
            if (oldToNewMap.containsKey(newOne.getId())) {
                oldToNewMap.remove(newOne.getId());
                oldToNewMap.replace(subjectId, newOne);
            }
        });
        //2.更新试卷题目
        //新增试卷
        List<SubjectHubVO> newList = new ArrayList<>(oldToNewMap.values());
        TestPaper newTestPaper = testPaperService.copy(newList, newTestPaperVO.getTestPaperId());

        //根据新试卷id ,新增试卷题目,绑定关系
        List<SubjectHub> subjectHubList = oldToNewMap.entrySet().stream()
                .map(e -> {
                    SubjectHubVO subjectHubVO = e.getValue();
                    subjectHubVO.setId(e.getKey());
                    SubjectHub subjectHub = new SubjectHub();
                    ConverterUtil.copyNotNullProperties(subjectHubVO, subjectHub);
                    return subjectHub;
                })
                .collect(Collectors.toList());
        //新建保存列表
        List<TestPaperSubject> saveList = new ArrayList<>();
        subjectHubList.forEach(e -> {
            TestPaperSubject testPaperSubject = new TestPaperSubject();
            testPaperSubject.setTestPaper(newTestPaper);
            testPaperSubject.setSubjectHub(e);
            //TODO 设置创建人
            saveList.add(testPaperSubject);
        });
        try {
            testPaperSubjectDao.saveAll(saveList);
            return newTestPaper;
        } catch (Exception e) {
            log.error(e.getMessage());
            throw new BaseException(ResultEnum.UPDATE_FAIL, e);
        }

    }

    @Override
    public Result updateTestPaperSubject(List<SubjectHubVO> oldSubjectHubVOList, EditTestPaperVO newTestPaperVO) {
//1.对比更新题目列表
        //把原先试卷列表转换成hashMap
        Map<Integer, SubjectHubVO> oldToNewMap = oldSubjectHubVOList.stream()
                .collect(Collectors.toMap(SubjectHubVO::getId, Function.identity()));
        //替换原有题目列表 使其成为新题目列表
        newTestPaperVO.getSubjectHubVOList().forEach(newOne -> {
            //新增题库题目
            Integer newSubjectId = subjectHubService.persist(newOne);
            //替换考试题目
            if (oldToNewMap.containsKey(newOne.getId())) {
                Integer column = testPaperSubjectDao.updateTestPaperSubject(newSubjectId, newTestPaperVO.getTestPaperId(), newOne.getId());
                if (column == 0) {
                    throw new BaseException(ResultEnum.UNKONW_ERROR);
                }
            }
        });
        return ResultUtil.success(ResultEnum.UPDATE_SUCCESS);
    }


}

